<template>
  <div class="app-container profile-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>个人资料</span>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="text-center">
            <el-avatar :size="100" :src="userAvatar">{{ userName.charAt(0).toUpperCase() }}</el-avatar>
            <h3 class="mt-2">{{ userName }}</h3>
            <p class="text-muted">{{ roleName }}</p>
            <el-button type="primary" plain @click="showChangePasswordDialog">修改密码</el-button>
          </div>
        </el-col>
        
        <el-col :span="16">
          <el-form label-width="100px" :model="userForm" :rules="rules" ref="userFormRef">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="用户名" />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" placeholder="姓名" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="邮箱" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">保存</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
      destroy-on-close
      append-to-body
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入旧密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPasswordForm" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { changePassword } from '@/api/user'

const userStore = useUserStore()
const userFormRef = ref(null)
const passwordFormRef = ref(null)
const passwordDialogVisible = ref(false)
const submitLoading = ref(false)

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单校验规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 用户信息
const userInfo = computed(() => userStore.userInfo || {})
const userName = computed(() => {
  const info = userInfo.value
  return info?.real_name || info?.name || info?.user_name || '用户'
})
const userAvatar = computed(() => userInfo.value?.avatar || '')
const roleName = computed(() => {
  const roles = userStore.roles || []
  return roles.includes('admin') ? '管理员' : '普通用户'
})

// 表单数据
const userForm = reactive({
  username: '',
  name: '',
  email: ''
})

// 表单校验规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ]
})

// 初始化用户表单数据
const initUserForm = () => {
  const info = userInfo.value
  if (info) {
    userForm.username = info.user_name || ''
    userForm.name = info.real_name || info.name || ''
    userForm.email = info.email || ''
  }
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备更新数据
        const updateData = {
          user_name: userForm.username,
          real_name: userForm.name,
          email: userForm.email
        }
        
        // 调用更新API
        await userStore.updateProfile(updateData)
        
        ElMessage.success('个人资料更新成功')
        
        // 重新获取用户信息并更新表单
        await userStore.getInfo()
        initUserForm()
      } catch (error) {
        console.error('更新个人资料失败:', error)
        ElMessage.error(error.message || '更新个人资料失败，请重试')
      }
    } else {
      return false
    }
  })
}

// 显示修改密码对话框
const showChangePasswordDialog = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

// 提交密码修改
const submitPasswordForm = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 调用修改密码API
        await changePassword({
          old_password: passwordForm.oldPassword,
          new_password: passwordForm.newPassword
        })
        
        ElMessage.success('密码修改成功')
        passwordDialogVisible.value = false
      } catch (error) {
        console.error('修改密码失败:', error)
        // ElMessage.error(error.response?.data?.message || '修改密码失败，请重试')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  initUserForm()
}

onMounted(() => {
  initUserForm()
})
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;
  
  .box-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .text-center {
    text-align: center;
    padding: 20px;
  }
  
  .mt-2 {
    margin-top: 10px;
  }
  
  .text-muted {
    color: #909399;
  }
}
</style>
